package com.example.grpc.client.service;

import com.example.grpc.client.dto.MessageResponseDTO;
import com.example.grpc.client.rpc.EndpointGrpcClient;
import com.example.grpc.client.rpc.GrpcChannelManager;
import io.grpc.ManagedChannel;
import org.springframework.stereotype.Component;
import proto.com.example.grpc.common.*;

@Component
public class MessageServiceClient extends EndpointGrpcClient<MessageServiceGrpc.MessageServiceBlockingStub> {

    public MessageServiceClient(GrpcChannelManager channelManager) {
        super(channelManager);
    }

    @Override
    protected String provideServiceName() {
        return "message-service";
    }

    @Override
    protected int provideServicePort() {
        return 20153;
    }

    @Override
    protected MessageServiceGrpc.MessageServiceBlockingStub createStub(ManagedChannel channel) {
        return MessageServiceGrpc.newBlockingStub(channel);
    }

    public MessageResponseDTO sendMessage(String content, String sender) {
        MessageProto.MessageRequest request = MessageProto.MessageRequest.newBuilder()
                .setContent(content)
                .setSender(sender)
                .setTimestamp(System.currentTimeMillis())
                .build();
        MessageProto.MessageResponse message = getStub().sendMessage(request);
        MessageResponseDTO from = MessageResponseDTO.from(message);

        return from;
    }
}